﻿using System;
using System.IO;
using System.Windows.Forms;
using BikeManageBusiness.logical;
using Data.Common;
using Data.Enum;
using Data.Model;
using DataAccess.AccountManage;
using DataAccess.BikeManage.logical;
using Ninject;
using WinForm.Helper;

namespace WinForm.SystemManage
{
    public partial class AddVipUser : Form
    {
        private static readonly IKernel Kernel = new StandardKernel(new DbModule());
        private readonly IAccount _account = Kernel.Get<IAccount>();

        public AddVipUser()
        {
            InitializeComponent();
        }

        private void buttonItem3_Click(object sender, EventArgs e)
        {
            tabAddUser.Show();
        }

        /// <summary>
        /// 读身份证信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveIDInfo_Click(object sender, EventArgs e)
        {
            string errorMessage = string.Empty;
            try
            {
                Dkqa16dLogical dkqa16DLogical = new Dkqa16dLogical();
                ResultInfo<IDCardData> idCardData = dkqa16DLogical.GetIdCardData();

                idCardData.ResultNumber = ResultEnum.Success;
                idCardData.Obj = new IDCardData() { Address = "长沙", Born = "19890110", GrantDept = "澧县公安局", IDCardNo = "323232323232323232", Name = "向钊豫", Nation = "china", PhotoFileName = @"C:\Users\xiangzy.CHANGSHA\Documents\Visual Studio 2010\Projects\BikeManage\WinForm\bin\Debug\070AE854D8D44577B75E14E88629B90C.jpg", reserved = "", Sex = "男", UserLifeBegin = "20101010", UserLifeEnd = "20201010" };

                if (idCardData.ResultNumber == ResultEnum.Success)
                {
                    //身份证信息赋值
                    txtName.Text = idCardData.Obj.Name;
                    txtGender.Text = idCardData.Obj.Sex;
                    txtNation.Text = idCardData.Obj.Nation;
                    txtHomeAddress.Text = idCardData.Obj.Address;
                    try
                    {
                        dateBorn.Value = Convert.ToDateTime(idCardData.Obj.Born);
                    }
                    catch (Exception)
                    {
                        dateBorn.Value = DateTime.Now;
                    }
                    txtIDNoR.Text = idCardData.Obj.IDCardNo;
                    txtIdGov.Text = idCardData.Obj.GrantDept;
                    userPicture.ImageLocation = idCardData.Obj.PhotoFileName;
                    //显示填用户信息界面
                    tabReadCard.Visible = false;
                    tabIdInfoShow.Visible = true;
                    //tabAddUser.SelectedTab = tabIdInfoShow;
                }
                else
                {
                    errorMessage = idCardData.Describe;
                }
            }
            catch (Exception e1)
            {
                errorMessage = e1.Message;
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }

        private void buttonX1_Click(object sender, EventArgs e)
        {
            string errorMessage = string.Empty;
            Zq58Logical zq58Logical = new Zq58Logical();
            ResultInfo<Decimal> initialMoney = zq58Logical.QueryPurse();
            if (initialMoney.ResultNumber == ResultEnum.Success)
            {
                lbInitialMoney.Text = initialMoney.Obj.ToString();
            }
            else
            {
                errorMessage = initialMoney.Describe;
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
            tabReadUserInfo.Visible = true;
            tabSaveOver.Visible = false;
        }

        /// <summary>
        /// 显示读出来的身份证信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnIdUp_Click(object sender, EventArgs e)
        {

            tabReadCard.Visible = true;
            tabIdInfoShow.Visible = false;
            //tabAddUser.SelectedTab = tabReadCard;
        }

        /// <summary>
        /// 显示读cpu卡的提示信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnIdNext_Click(object sender, EventArgs e)
        {
            tabIdInfoShow.Visible = false;
            tabReadCpu.Visible = true;
        }

        /// <summary>
        /// 回到身份证信息展示页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReadCpuUp_Click(object sender, EventArgs e)
        {
            tabIdInfoShow.Visible = true;
            tabReadCpu.Visible = false;
        }

        /// <summary>
        /// 测试cpu卡是否放好，显示读cpu卡的提示页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReadCpuNext_Click(object sender, EventArgs e)
        {
            string errorMessage = string.Empty;
            Zq58Logical zq58Logical = new Zq58Logical();
            ResultInfo<string> checkCpuEquipment = zq58Logical.CheckCpuEquipment();
            if (checkCpuEquipment.ResultNumber == ResultEnum.Success)
            {
                txtIDNo.Text = txtIDNoR.Text;
                txtCpuNo.Text = checkCpuEquipment.Obj;

                dateValided.Value = DateTime.Now.AddYears(3);
                cmbIDType.SelectedIndex = 0;
                cmbCpuVersion.SelectedIndex = 0;
                cmbIDType.SelectedIndex = 0;
                cmbCpuType.SelectedIndex = 0;

                tabReadUserInfo.Visible = true;
                tabReadCpu.Visible = false;
            }
            else
            {
                errorMessage = errorMessage + checkCpuEquipment.Describe;
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }

        /// <summary>
        /// 返回度cpu卡的提示信息界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCpuUp_Click(object sender, EventArgs e)
        {
            tabReadCpu.Visible = true;
            tabReadUserInfo.Visible = false;
        }

        /// <summary>
        /// 返回用户卡信息输入界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX1_Click_1(object sender, EventArgs e)
        {
            tabSaveOver.Visible = false;
            tabReadUserInfo.Visible = true;
        }

        /// <summary>
        /// 保存用户信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            string errorMessage = string.Empty;
            try
            {
                Zq58Logical zq58Logical = new Zq58Logical();
                //获取cpu卡用户信息
                CpuAccount cpuAccount = new CpuAccount();
                cpuAccount.CpuCardNo = txtCpuNo.Text;
                cpuAccount.CpuCardVersion = cmbCpuVersion.Text;
                if (radioButton1.Checked)
                {
                    cpuAccount.CpuCardStatus = radioButton1.Text;
                }
                else if (radioButton2.Checked)
                {
                    cpuAccount.CpuCardStatus = radioButton2.Text;
                }
                else if (radioButton3.Checked)
                {
                    cpuAccount.CpuCardStatus = radioButton3.Text;
                }
                else
                {
                    cpuAccount.CpuCardStatus = radioButton1.Text;
                }
                cpuAccount.CpuCardType = cmbCpuType.Text;
                cpuAccount.DisplayName = txtName.Text;
                cpuAccount.Fee = txtFee.Text;
                cpuAccount.Address = txtAddress.Text;
                cpuAccount.IdCardNo = txtIDNo.Text;
                cpuAccount.IdCardType = cmbIDType.Text;
                cpuAccount.Mobile = txtPhoneNo.Text;
                cpuAccount.Phone = txtTel.Text;
                cpuAccount.Sex = txtGender.Text;
                cpuAccount.Nation = txtNation.Text;

                ResultInfo<byte[]> writeAccount = zq58Logical.WriteAccountInfo(cpuAccount);
                if (writeAccount.ResultNumber == ResultEnum.Success)
                {
                    ResultInfo<byte[]> borroBike = zq58Logical.WriteBorrowBikeInfo(new BorrowBike() { OpenAccountDate = Converts.ConvertDateToString(DateTime.Now), EndAccountDate = Converts.ConvertDateToString(DateTime.Now.AddYears(3)) });//这里是指为了写开户日期跟有效期
                    if (borroBike.ResultNumber == ResultEnum.Success)
                    {
                        Decimal money = Converts.ConvertToDecimal(tbInitialCzMoney.Text);
                        ResultInfo<byte[]> purseMoney = zq58Logical.PurseSave(money);
                        if (purseMoney.ResultNumber == ResultEnum.Success)
                        {
                            ResultInfo<Decimal> queryMoney = zq58Logical.QueryPurse();
                            if (queryMoney.ResultNumber == ResultEnum.Success)
                            {
                                lbTotalMoney.Text = queryMoney.Obj.ToString();

                                //保存到数据库之前先查询用户卡的信息
                                ResultInfo<CpuAccount> newAccount = zq58Logical.ReadAccountInfo();
                                if (newAccount.ResultNumber == ResultEnum.Success)
                                {
                                    //将信息存入数据库

                                    try
                                    {
                                        var jshAccount = new jsh_account
                                        {
                                            addr1 = txtHomeAddress.Text,
                                            addr2 = txtAddress.Text,
                                            balance = Converts.ConvertToDecimal(queryMoney.Obj.ToString()),
                                            cardtype = newAccount.Obj.CpuCardType,
                                            closedate = dateValided.Value,
                                            cpuid = newAccount.Obj.CpuCardId,
                                            cpuno = newAccount.Obj.CpuCardNo,
                                            credit = 0,
                                            deposit = Converts.ConvertToDecimal(tbReceipt.Text),
                                            edate = dateValided.Value.ToString(),
                                            fzdw = txtIdGov.Text,
                                            khdate = DateTime.Now.ToString(),
                                            validate = dateValided.Value.ToString(),
                                            memo = txtMemo.Text,
                                            mobile = newAccount.Obj.Mobile,
                                            nation = newAccount.Obj.Nation,
                                            operator1 = "admin",
                                            operatorid = 0,
                                            password = txtPassword.Text
                                        };
                                        try
                                        {
                                            System.IO.StreamReader reader = new StreamReader(userPicture.ImageLocation);
                                            System.IO.Stream stream = reader.BaseStream;
                                            byte[] imgs = new byte[stream.Length];
                                            stream.Read(imgs, 0, imgs.Length);
                                            jshAccount.photo = imgs;
                                        }
                                        catch (Exception)
                                        {

                                        }
                                        jshAccount.sdate = DateTime.Now.ToString();
                                        jshAccount.sex = newAccount.Obj.Sex;
                                        jshAccount.status = newAccount.Obj.CpuCardStatus;
                                        jshAccount.telephone = newAccount.Obj.Phone;
                                        jshAccount.username = newAccount.Obj.DisplayName;
                                        jshAccount.zzhm = newAccount.Obj.IdCardNo;
                                        jshAccount.zzlx = newAccount.Obj.IdCardType;

                                        ResultInfo<bool> openAccount = _account.OpenAccount(jshAccount, Converts.ConvertToDecimal(lbInitialMoney.Text),
                                                              Converts.ConvertToDecimal(tbInitialCzMoney.Text),
                                                              Converts.ConvertToDecimal(tbReceipt.Text), SystemInfo.OperateAddress, SystemInfo.OperateAddressId, SystemInfo.OperatePsamId);
                                        if (openAccount.ResultNumber == ResultEnum.Success)
                                        {
                                            if (openAccount.Obj)
                                            {
                                                if (MyMessageBox.ShowMessageBoxQuestion(string.Format("保存用户信息到用户卡成功！账户初始金额为：{0}元，本次充值：{1}元，当前余额：{2}元", lbInitialMoney.Text, lbCzMoney.Text, lbTotalMoney.Text)) == DialogResult.Yes)
                                                {
                                                    this.Dispose();
                                                }
                                            }
                                        }
                                        else
                                        {
                                            //如果存入数据库没有成功，扣除刚刚充值到cpu卡的钱
                                            ResultInfo<byte[]> backMoney =
                                                zq58Logical.CostMoney(
                                                    Converts.ConvertToDecimal(tbInitialCzMoney.Text));
                                            if (backMoney.ResultNumber != ResultEnum.Success)
                                            {
                                                errorMessage = errorMessage + backMoney.Describe;
                                            }
                                            errorMessage = errorMessage + openAccount.Describe;
                                        }
                                    }
                                    catch (Exception e1)
                                    {
                                        errorMessage = errorMessage + e1.Message;
                                    }
                                }
                                else
                                {
                                    errorMessage = errorMessage + newAccount.Describe;
                                }
                            }
                            else
                            {
                                lbTotalMoney.Text = queryMoney.Describe;
                            }
                        }
                        else
                        {
                            errorMessage = errorMessage + purseMoney.Describe;
                        }
                    }
                    else
                    {
                        errorMessage = errorMessage + borroBike.Describe;
                    }
                }
                else
                {
                    errorMessage = errorMessage + writeAccount.Describe;
                }
            }
            catch (Exception e1)
            {
                errorMessage = errorMessage + e1.Message;
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }

        /// <summary>
        /// 展示所有输入的信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCpuNext_Click(object sender, EventArgs e)
        {
            string errorMessage = string.Empty;
            //if (txtValideDays.Text.Length > 7)
            //{
            //    errorMessage = "输入的有效天数不能超过7位数";
            //}
            if (string.IsNullOrEmpty(txtName.Text))
            {
                errorMessage = "用户名不能为空";
            }
            if (string.IsNullOrEmpty(txtPassword.Text) || (txtPassword.Text != txtPassword1.Text))
            {
                errorMessage = "密码为空或者两次输入密码不一致";
            }
            if (string.IsNullOrEmpty(txtIDNo.Text))
            {
                errorMessage = "证件号码不能为空";
            }
            if (string.IsNullOrEmpty(txtPhoneNo.Text) && string.IsNullOrEmpty(txtTel.Text))
            {
                errorMessage = "手机号或者座机号必须至少留一个";
            }
            Zq58Logical zq58Logical = new Zq58Logical();
            ResultInfo<Decimal> initialMoney = zq58Logical.QueryPurse();
            if (initialMoney.ResultNumber == ResultEnum.Success)
            {
                lbInitialMoney.Text = initialMoney.Obj.ToString();
            }
            else
            {
                errorMessage = initialMoney.Describe;
            }
            try
            {
                if (string.IsNullOrEmpty(errorMessage))
                {
                    //初始化用户信息显示
                    lbName.Text = txtName.Text;
                    lbSex.Text = txtGender.Text;
                    lbNation.Text = txtNation.Text;
                    lbValideDate.Text = dateValided.Value.ToString();
                    lbCpuVersion.Text = cmbCpuType.Text;
                    if (radioButton1.Checked)
                    {
                        lbStatus.Text = radioButton1.Text;
                    }
                    else if (radioButton2.Checked)
                    {
                        lbStatus.Text = radioButton2.Text;
                    }
                    else if (radioButton3.Checked)
                    {
                        lbStatus.Text = radioButton3.Text;
                    }
                    else
                    {
                        lbStatus.Text = radioButton1.Text;
                    }
                    lbCpuType.Text = cmbCpuType.Text;
                    lbFee.Text = txtFee.Text;
                    lbIdGov.Text = txtIdGov.Text;
                    lbIdNo.Text = txtIDNoR.Text;
                    lbIdType.Text = cmbIDType.Text;
                    lbMobile.Text = txtPhoneNo.Text;
                    lbTel.Text = txtTel.Text;
                    lbCzMoney.Text = tbInitialCzMoney.Text;
                    lbBorn.Text = dateBorn.Value.ToString();
                    lbHomeAddr.Text = txtHomeAddress.Text;
                    lbCurrentAddr.Text = txtAddress.Text;
                    lbCpuNo.Text = txtCpuNo.Text;
                    lbReceipt.Text = tbReceipt.Text;
                    lbMemo.Text = txtMemo.Text;
                    lbCpuVersion.Text = cmbCpuVersion.Text;
                    pictureBox1.ImageLocation = userPicture.ImageLocation;
                    tabReadUserInfo.Visible = false;
                    tabSaveOver.Visible = true;
                }
                else
                {
                    MyMessageBox.ShowMessageBoxError(errorMessage);
                }
            }
            catch (Exception e1)
            {
                MyMessageBox.ShowMessageBoxError(e1.Message);
            }
        }

        private void btnPasswordCancel_Click(object sender, EventArgs e)
        {
            this.Close();
            this.Dispose();
        }

        private void btnSaveIdPrevious_Click(object sender, EventArgs e)
        {
            tabPassword.Visible = true;
            tabReadCard.Visible = false;

            tabAddUser.SelectedTab = tabPassword;
        }

        private void btnPasswordNext_Click(object sender, EventArgs e)
        {
            string errorMessage = string.Empty;
            if (string.IsNullOrEmpty(textBoxX1.Text))
            {
                errorMessage = errorMessage + "密码为空";
            }
            else
            {
                tabReadCard.Visible = true;
                tabPassword.Visible = false;
                tabAddUser.SelectedTab = tabReadCard;
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }
    }
}
